package multithread.framework.xml;

import multithread.framework.constant.XMLConfigConstant;
import multithread.framework.threadmethod.ThreadMethod;

import org.jdom.Element;

public class MethodElement extends Element implements IVerifiable {
	private static final long serialVersionUID = -8617466237566602646L;
	private Element params;

	public MethodElement(ThreadMethod threadMethod) {
		this(threadMethod, false);
	}

	/**
	 * @param threadMethod
	 *            ThreadMethod
	 */
	public MethodElement(ThreadMethod threadMethod, boolean isCommon) {
		super(XMLConfigConstant.METHOD_ELEMENT);
		setAttribute(XMLConfigConstant.NAME_PROPERTY, threadMethod
				.getIvokeMthod().getName());
		if (threadMethod.getThreadFor() != null && !isCommon) {
			setThreadCount(threadMethod.getThreadFor().value());
		}
		// add parameter element
		Class<?>[] parameterTypes = threadMethod.getMethodParamTypes();
		Object[] parameterValues = threadMethod.getMethodParams();
		for (int i = 0; i < parameterTypes.length; i++) {
			addParamElement(ParamElement.createParamElement(parameterTypes[i],
					parameterValues[i]));
		}
	}

	public void setThreadCount(Integer threadCount) {
		if (threadCount != null && threadCount > 0) {
			setAttribute(XMLConfigConstant.THREAD_PROPERTY,
					threadCount.toString());
		}
	}

	public Element addParamElement(ParamElement paramElement) {
		if (paramElement != null && paramElement.validate()) {
			synchronized (this) {
				if (params == null) {
					params = new Element(XMLConfigConstant.POARAMS_ELEMENT);
					addContent(params);
				}
			}
			return params.addContent(paramElement);
		}
		return null;
	}

	/**
	 * check the method element is validation
	 * 
	 * @return true or false
	 */
	public boolean validate() {
		return true;
	}
}